package com.witdata.rabbit.service.impl;

import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.InstanceDto;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.mapper.InstanceMapper;
import com.witdata.common.util.IdUtils;
import com.witdata.mysql.base.service.InstanceBaseService;
import com.witdata.mysql.domain.entity.TInstance;
import com.witdata.rabbit.service.InstanceService;
import com.witdata.rabbit.producer.InstanceProducer;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class InstanceServiceImpl implements InstanceService {
    private final InstanceBaseService instanceBaseService;
    private final InstanceProducer instanceProducer;

    @Override
    public List<InstanceDto> getInstanceList() {
        List<TInstance> tInstanceList = instanceBaseService.list();
        return InstanceMapper.INSTANCE.toInstanceDtoList(tInstanceList);
    }

    @Override
    @Transactional
    public InstanceDto registerInstance(InstanceDto instanceDto) {
        if (!ObjectUtils.isEmpty(instanceDto)) {
            TInstance tInstance = InstanceMapper.INSTANCE.toTInstance(instanceDto);
            tInstance.setName(StringUtils.hasText(instanceDto.getName()) ? instanceDto.getName() : "未命名");
            tInstance.setId(IdUtils.createId());
            tInstance.setStatus(instanceDto.getStatus().name());
            tInstance.setCreated(LocalDateTime.now());
            tInstance.setUpdated(LocalDateTime.now());
            tInstance.setMemoryUsage((int) (tInstance.getUsedMemory() * 100 / tInstance.getTotalMemory()));
            instanceBaseService.save(tInstance);
            return InstanceMapper.INSTANCE.toInstanceDto(tInstance);
        }
        return null;
    }

    @Override
    public void updateInstance(InstanceDto instanceDto) {
        if (!ObjectUtils.isEmpty(instanceDto)) {
            TInstance tInstance = InstanceMapper.INSTANCE.toTInstance(instanceDto);
            tInstance.setUpdated(LocalDateTime.now());
            instanceBaseService.updateById(tInstance);
        }
    }

    @Override
    public InstanceDto getInstanceById(Long instanceId) {
        TInstance tInstance = instanceBaseService.getById(instanceId);
        return InstanceMapper.INSTANCE.toInstanceDto(tInstance);
    }

    @Override
    public void deleteInstance(Long id) {
        boolean removed = instanceBaseService.removeById(id);
        if (!removed) {
            throw new GlobalException(Status.REMOVEERROR);
        }
    }
}
